<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <img src="@/assets/rabbit-logo.svg" alt="兔溯源" class="logo">
        <h1>爱吃兔溯源管理系统</h1>
        <p>专业的兔子品种溯源与养殖监控平台</p>
      </div>
      <el-card class="login-form-card" shadow="hover">
        <div class="form-title">用户登录</div>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" size="large">
          <el-form-item label="" prop="UserName">
            <el-input v-model="ruleForm.UserName" placeholder="请输入用户名" prefix-icon="el-icon-user">
              <template #prefix>
                <i class="el-icon-user">👤</i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="" prop="Password">
            <el-input v-model="ruleForm.Password" show-password placeholder="请输入密码">
              <template #prefix>
                <i class="el-icon-lock">🔒</i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="" prop="captcha">
            <div class="captcha-container">
              <el-input v-model="ruleForm.captcha" placeholder="请输入验证码" class="captcha-input" />
              <div @click="refreshCaptcha" class="captcha-code">
                {{ captchaText }}
              </div>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)" class="login-btn">
              登录系统
            </el-button>
          </el-form-item>
          <div class="login-footer">
            <p>爱吃兔溯源系统 - 专注兔类品种溯源与健康管理</p>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>

</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useCounterStore } from '@/stores/counter'
import { readB, writeB } from "@/https/http"


const counterstore = useCounterStore();
const router = useRouter();
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  UserName: '',
  Password: '',
  captcha: ''
})

const captchaText = ref('')

// 生成随机字母验证码
const generateCaptcha = () => {
  const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZqazwsxedcrfvtgbyhnujmiklop'
  let result = ''
  for (let i = 0; i < 4; i++) {
    result += letters.charAt(Math.floor(Math.random() * letters.length))
  }
  return result
}

// 刷新验证码
const refreshCaptcha = () => {
  captchaText.value = generateCaptcha()
  ruleForm.captcha = ''
}

// 组件挂载时生成验证码
onMounted(() => {
  refreshCaptcha()
})

const rules = reactive<FormRules>({
  UserName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },

  ],
  Password: [
    { required: true, message: '请输入密码', trigger: 'blur' },

  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value || value.toUpperCase() !== captchaText.value.toUpperCase()) {
          callback(new Error('验证码错误'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      readB.get("/RBACMenganment/Login", { params: ruleForm })
        .then(res => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.message);
            
            // 确保数据存在
            if (!res.data.data || !res.data.data.token) {
              ElMessage.error('登录返回数据不完整，请重试');
              return;
            }
            
            // 保存用户信息
            counterstore.userinfo.username = res.data.data.userName || '';
            counterstore.userinfo.RoleAllName = res.data.data.allRoles || '';
            counterstore.userinfo.roleIds = res.data.data.roleId || [];
            
            // 登录成功，写JWT的 token到本地
            window.localStorage.setItem("token", res.data.data.token);
            
            // 数据提交后端要加入新的Token值
            axios.defaults.headers.common["Authorization"] = "Bearer " + res.data.data.token;
            
            // 使用 nextTick 确保状态更新后再导航
            setTimeout(() => {
              router.push("/Index");
            }, 300);
          }
          else {
            ElMessage.error(res.data.message || '登录失败，请重试');
          }
        })
        .catch(error => {
          console.error('登录请求失败:', error);
          ElMessage.error('登录请求失败，请检查网络连接或联系管理员');
        });
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  refreshCaptcha()
}

</script>

<style scoped>
.login-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #e8f4ff 0%, #f0f9e8 100%);
  position: relative;
  overflow: hidden;
}

.login-container::before {
  content: "";
  position: absolute;
  width: 300px;
  height: 300px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><path d="M50,30 C55,10 75,10 80,30 C85,10 95,20 90,40 C95,50 90,70 80,70 C75,80 55,80 50,70 C45,80 25,80 20,70 C10,70 5,50 10,40 C5,20 15,10 20,30 C25,10 45,10 50,30 Z" fill="rgba(255,192,203,0.1)"/></svg>');
  background-repeat: no-repeat;
  background-size: contain;
  top: -100px;
  right: -100px;
  transform: rotate(30deg);
  opacity: 0.6;
  z-index: 1;
}

.login-container::after {
  content: "";
  position: absolute;
  width: 200px;
  height: 200px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><path d="M30,30 C40,20 60,20 70,30 C80,40 80,60 70,70 C60,80 40,80 30,70 C20,60 20,40 30,30 Z" fill="rgba(144,238,144,0.1)"/></svg>');
  background-repeat: no-repeat;
  background-size: contain;
  bottom: -50px;
  left: -50px;
  transform: rotate(-15deg);
  opacity: 0.6;
  z-index: 1;
}

.login-box {
  width: 460px;
  z-index: 2;
}

.login-header {
  text-align: center;
  margin-bottom: 20px;
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 10px;
}

.login-header h1 {
  color: #4a9668;
  font-size: 28px;
  margin: 0;
  font-weight: bold;
}

.login-header p {
  color: #666;
  font-size: 14px;
  margin: 8px 0 0;
}

.login-form-card {
  border-radius: 10px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1) !important;
  background-color: white;
  padding: 10px;
}

.form-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin: 0 0 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.captcha-container {
  display: flex;
  align-items: center;
}

.captcha-input {
  flex: 1;
  margin-right: 10px;
}

.captcha-code {
  font-size: 20px;
  letter-spacing: 5px;
  font-weight: bold;
  cursor: pointer;
  user-select: none;
  padding: 5px 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
  color: #333;
  border: 1px dashed #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 100px;
}

.captcha-code:hover {
  background-color: #f0f0f0;
}

.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  border-radius: 4px;
  background: linear-gradient(135deg, #67c23a 0%, #4a9668 100%);
  border: none;
  margin-top: 10px;
}

.login-btn:hover {
  background: linear-gradient(135deg, #5daf34 0%, #40805a 100%);
}

.login-footer {
  text-align: center;
  margin-top: 15px;
}

.login-footer p {
  color: #999;
  font-size: 12px;
}

:deep(.el-input__wrapper) {
  padding: 1px 11px;
}

:deep(.el-input__prefix) {
  margin-right: 8px;
}
</style>
